import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
import {SelectorOption} from './selector-option';
import {FormBuilder, FormGroup, ValidationErrors} from '@angular/forms';
import {deepCopy} from '../../functions/copy';

@Component({
  selector: 'ng-tools-selector',
  templateUrl: './selector.component.html',
  styleUrls: ['./selector.component.scss']
})
export class SelectorComponent implements OnInit {
  @Input() selector: { search: SelectorOption, choiceItems: SelectorOption[], dateTimeRange: SelectorOption };
  @Output() selected = new EventEmitter();
  selectForm = null;
  selectResult;
  showCollapse = false;

  constructor(private formBuilder: FormBuilder) {
  }

  confirmed() {
    this.emitEvent();
  }

  toggleCollapse() {
    this.showCollapse = !this.showCollapse;
  }

  enter(e) {
    e.stopPropagation();
    if (e.keyCode === 13 && this.selectForm.valid) {
      this.emitEvent();
    }
  }

  emitEvent() {
    this.setSelectResult();
    this.selected.emit({
      normal: this.selectResult,
      forPaginationService: this.forPaginationService(this.selectResult)
    });
  }


  setSelectResult() {
    this.selectResult = {};
    const formValue = deepCopy(this.selectForm.value);
    if (this.selector.choiceItems && this.selector.choiceItems.length > 0) {
      for (const item of this.selector.choiceItems) {
        formValue[item.name].forEach((checked, index) => {
          if (checked) {
            if (!this.selectResult[item.name]) {
              this.selectResult[item.name] = [];
            }
            this.selectResult[item.name].push(item.choices[index].value);
          }
        });
      }
    }
    const search = this.selector.search;
    if (formValue[search.name]) {
      this.selectResult[search.name] = formValue[search.name];
    }
    const dateAndTime = this.selector.dateTimeRange;
    if (this.selector.dateTimeRange !== undefined) {
      const dateTimeRange = this.orderDateAndTimeData(this.selectForm.controls[this.selector.dateTimeRange.name + '_start_date_time'].value,
        this.selectForm.controls[this.selector.dateTimeRange.name + '_end_date_time'].value);
      console.log(dateTimeRange);
      if (dateTimeRange !== '') {
        this.selectResult[dateAndTime.name] = dateTimeRange;
      }
    }
  }

  orderDateAndTimeData(selectStartDate: string, selectEndDate: string) {
    if ((selectStartDate === '' && selectEndDate === '') || (selectStartDate === null && selectEndDate === null)) {
      return '';
    }
    let startTime;
    let endTime;
    if (selectStartDate === '') {
      startTime = '';
    } else {
      startTime = selectStartDate;
    }
    if (selectEndDate === '') {
      endTime = '';
    } else {
      endTime = selectEndDate;
    }
    const dateTimeRange = [];
    dateTimeRange.push(this.timeToTimeStamp(startTime));
    dateTimeRange.push(this.timeToTimeStamp(endTime));
    return dateTimeRange;
  }

  timeToTimeStamp(strtime) {
    if (strtime !== null) {
      if (strtime === '') {
        return 0;
      }
      const date = new Date(strtime.replace(/-/g, '/'));
      return date.getTime() * 1000;
    }
  }

  forPaginationService(obj) {
    // 把结果转换成分页服务可用的形式
    const params = [];
    Object.keys(obj).forEach((key) => {
      if (this.selector.hasOwnProperty('dateTimeRange')) {
      if (Object.prototype.toString.call(obj[key]) === '[object Array]' && key !== this.selector.dateTimeRange.name) {
        for (const value of obj[key]) {
          params.push({key: key, value: value, op: 'a'});
        }
      }} else {
        if (Object.prototype.toString.call(obj[key]) === '[object Array]') {
          for (const value of obj[key]) {
            params.push({key: key, value: value, op: 'a'});
          }
        } else {
        params.push({key: key, value: obj[key], op: 's'});
        }
      }
    });
    return params;
  }

  reset() {
    this.selectForm.reset();
    this.emitEvent();
  }

  buildForm() {
    const formGroupOptions = {};
    if (this.selector.choiceItems && this.selector.choiceItems.length > 0) {
      for (const item of this.selector.choiceItems) {

        const controls = [];
        for (const choice of item.choices) {
          controls.push(this.formBuilder.control(choice.flag));
        }
        formGroupOptions[item.name] = this.formBuilder.array(controls);
      }
    }
    formGroupOptions[this.selector.search.name] = this.formBuilder.control('');
    if (this.selector.dateTimeRange !== undefined) {
      formGroupOptions[this.selector.dateTimeRange.name + '_start_date_time'] = this.formBuilder.control('');
      formGroupOptions[this.selector.dateTimeRange.name + '_end_date_time'] = this.formBuilder.control('');
    }
    this.selectForm = this.formBuilder.group(formGroupOptions, {validator: this.validator});
  }

  validator(group: FormGroup): ValidationErrors {
    let valid = false;
    const values = group.value;
    const properties = Object.keys(values);
    for (const prop of properties) {
      if (Object.prototype.toString.call(values[prop]) === '[object Array]') {
        for (const v of values[prop]) {
          if (v) {
            valid = true;
            break;
          }
        }
        if (valid) {
          break;
        }
      } else {
        if (values[prop]) {
          valid = true;
          break;
        }
      }
    }
    return valid ? null : {'msg': 'invalid'};
  }

  ngOnInit() {
    this.buildForm();
  }
}


